import {
  Base
} from "base.js"
import {
  Shopcart
} from "shopcart.js"
import {
  Token
} from "../utils/token.js"
import
 {
  Enum
} from "../utils/enum.js"
import {
  VirtualPay
} from "../utils/virtualPay.js"

var virtualPay = new VirtualPay()
var token = new Token()

class Order extends Base {
  constructor() {
    super()
  }

  placeOrder(bookArray, shopcartKey, orderType) {
    var data = {}
    data.books = this._processBooks(bookArray)
    data.type = orderType
    // data = JSON.stringify(data)
    var params = {
      url: "order",
      data: data,
      method: "POST",
      fn: (res) => {
        if (this.processRes(res.statusCode)) {
          this._getOrderData(res, shopcartKey, orderType)
        }
      }
    }
    this.request(params)
  }

  // 下单完成之后
  operateOrder(order, fromWhere, PaySuccessFn) {
    if (order.status == Enum.orderStatus.DELIVERED) {
      //  看物流
      var params = {
        url: "express/get?id=" + order.id,
        method: "GET",
        fn: (res) => {
          if (this.processRes(res.statusCode)) {
            if(res.data.express_no){
              wx.showModal({
                title: res.data.comp_name,
                content: "快递单号：" + res.data.express_no,
              })
            }
            else{
              this.toast("暂无物流信息",none)
            }
          }
        }
      } 
      // this.toast("暂无物流信息", "none")
      this.request(params)
      return
    }

    if (order.status == Enum.orderStatus.UNPAID) {
      if (order.order_type == Enum.orderType.recycleOrder) {
        // 发货
        wx.navigateTo({
          url: '/pages/express/express?id=' + order.id + "&fromWhere=" + fromWhere
        })
      }

      if (order.order_type == Enum.orderType.buyOrder) {
        // 确定支付吗？
        wx.showModal({
          title: '支付订单',
          content: '点击确定支付订单',
          success:(res)=>{
            if (res.confirm) {
              virtualPay.toPay(order.id, (res) => {
                this.checkOrderStatusRes(res, PaySuccessFn)
              })
            }
          }
        })
      }
    }
  }

  checkOrderStatusRes(res, fn) {
    // ok 201
    if (this.processRes(res.statusCode)) {
      fn && fn(res)
    }

    // 库存不足 400  余额不足 400
    else if (res.statusCode == 400) {
      this.toast(res.data.info, "none")
    }

    // 其他错误 500
    else {
      this.toast("出错了，请稍后再试", "none")
    }
  }

  /**
   * 用户发货完成后 返回 需要更新页面
   * fromOrder 从order页面跳转到发货页面  更新 Order、OrderList
   * fromOrderList 从OrderList页面跳转到发货页面  更新 OrderList
   */

  /**
   * 支付完
   * fromOrder 从order页面跳转到OrderList  更新 OrderList
   * fromOrderList  OrderList直接支付  不网络更新  修改页面数据
   */
  setUpdateStorage(fromWhere) {
    // 从 发货  返回
    if (fromWhere == Enum.fromOrder) {
      wx.setStorageSync(Enum.fromOrder, true)
      wx.setStorageSync(Enum.fromOrderList, true)
    }

    // 从 order详情  返回
    if (fromWhere == Enum.fromOrderList) {
      wx.setStorageSync(Enum.fromOrderList, true)
    }
  }


  // order snap 的状态
  getOrderText(statusNO, orderType) {
    var enumOrder
    var result = {}
    if (orderType == Enum.orderType.recycleOrder) {
      enumOrder = Enum.recycleOrder
    } else {
      enumOrder = Enum.buyOrder
    }
    for (var key in Enum.orderStatus) {
      if (Enum.orderStatus[key] == statusNO) {
        return (enumOrder[key])
      }
    }
  }

  getOrderList(data, callback) {
    var params = {
      url: "order/list",
      data: data,
      fn: (res) => {
        callback && callback(res)
      }
    }
    this.request(params)
  }

  getOrderDetail(orderID, callback) {
    var params = {
      url: "order/" + orderID,
      fn: (res) => {
        callback && callback(res)
      }
    }
    this.request(params)
  }

  /**
   * 看订单类型
   * buy -- 用户支付
   * recycle -- 用户发货
   */
  _getOrderData(res, shopcartKey, orderType) {
    var shopcart = new Shopcart(shopcartKey)
    if (res.data.pass) {

      // 生成订单成功  
      // 更新购物车
      shopcart.updataShopcart()

      this.toast("下单成功")
      // 去支付 且 关闭下单页面

      // set time out 为了让 toast 有时间显示
      setTimeout(function() {
        wx.redirectTo({
          url: '/pages/order-list/order-list?orderType=' + orderType,
        })
      }, 1000)


    } else {
      this.toast("库存不足，将返回购物车", "none")
      // 将购物车的库存减到能下单的 数量
      shopcart.lowStock(res.data.bookStatusArray)

      // 跳转回购物车
      setTimeout(function() {
        wx.navigateBack({
          delta: 1
        })
      }, 1000)

    }
  }

  // 将bookArray数据转换成 api 需要的
  _processBooks(bookArray) {
    var result = []
    bookArray.forEach(item => {
      result.push({
        book_id: item.id,
        count: item.count
      })
    })
    return result
  }
}
export {
  Order
}